<?php
namespace Admin\Controller;

class ContestController extends AdminController {
	/**
	 * 比赛信息
	 *
	 * 		获取页面参数，
	 * 			通过教师id，比赛状态，多表查询到班级比赛信息。
	 */
    public function index(){
        $state=I('state');//比赛状态
        $book_game_name=I('book_game_name');
        $map['book_game_name']=   array('like', '%'.(string)$book_game_name.'%');
		switch ($state){
			//isready 是否开启（0，表示已结束，1，表示未开始，2表示已开始，默认为1）
			case 'notstart'://未开始
				$map['isready']=1;
				$order='id desc';
				break;
			case 'underway'://进行中
				$map['isready']=2;
				$order='start_time desc';
				break;
			case 'over'://结束
				$map['isready']=0;
				$order='end_time desc';
				break;
		}
		$map['status']	=	1;//状态（-1：已删除，0：禁用，1：正常）
		$map['schoolid']=	session('user_auth.schoolid');
        $contestList   	= 	$this->lists('BookGame', $map, $order);
		$this->assign('isready',$map['isready']);
        $this->assign('_list', $contestList);
        Cookie('__forward__',$_SERVER['REQUEST_URI']);
        $this->display();
    }
    /**
     * 获得图书ID和名称
     */
    public function getBooks(){
    	$map['bld.seriesid']    =  I('post.seriesid');
    	$bookData = M('BookListDetail bld')->join('primary_book_info bi ON bld.bookid=bi.id AND bi.status=1')
    				->where($map)
    				->field('bld.bookid,bi.bookname')
    				->select();
    	$this->ajaxReturn($bookData,'JSON');

    }
    
    public function add(){
    	if(IS_POST){
    		$bookGame   =  D('BookGame');
    		$gameInfo   =  $bookGame->create();
    		if(!$gameInfo){
    			$this->error($bookGame->getError());
    		}else{
    			$gameInfo['status']      =  1;
    			$gameInfo['isready']     =  1;
    			$gameInfo['schoolid']    =  session('user_auth.schoolid');
    			$gameInfo['schoolname']  =  session('user_auth.schoolname');
    			if(!$bookGame->add($gameInfo)){
    				$this->error('添加比赛失败！');
    			}else {
    				$this->success('添加比赛成功！',Cookie('__forward__'));
    			}
    		}
    	}else{
	    	//显示图书系列
			$seriesMap['schoolid']	=	session('user_auth.schoolid');
			$seriesMap['status']	=	1;
	    	$seriesList				=	M('BookList')->where($seriesMap)->select();
	    	$this->assign('series',$seriesList);
	
	    	$classMap['status']			=	1;//班级状态（-1：已删除，0：禁用，1：正常）
	    	$classMap['undergraduate']	=	1;//是否毕业（1，表示未毕业，0表示已毕业）
	    	$classMap['schoolid']		=	session('user_auth.schoolid');
	    	$class					=	M('ClassInfo')->where($classMap)->select();
	    	$this->assign('class',$class);
	    	$this->display();
    	}
    }
    
    public function edit(){
    	if(IS_POST){
    		$bookGame   =  D('BookGame');
    		$gameInfo   =  $bookGame->create();
    		if(!$gameInfo){
    			$this->error($bookGame->getError());
    		}else{
    			if($bookGame->save($gameInfo)===false){
    				$this->error('修改比赛失败！');
    			}else {
    				$this->success('修改比赛成功！',Cookie('__forward__'));
    			}
    		}
    	}else{
		    $bookGameId	=	I('id');
		    	
		    //查询比赛名称
	    	$contest	=	M('BookGame')->find($bookGameId);
	
			//查询比赛书目
			$bookList	=	M('BookInfo')->select($contest['bookids']);
	    	$this->assign('book_list',$bookList);
	    	
	    	//查询参与比赛班级
			$classMap['id']			=	array('in',$contest['classids']);
			$contest['class']		=	M('ClassInfo')->where($classMap)->select();
	    	
			//查询剩余班级
	    	$map['status']			=	1;//班级状态（-1：已删除，0：禁用，1：正常）
	    	$map['undergraduate']	=	1;//是否毕业（1，表示未毕业，0表示已毕业）
	    	$map['schoolid']		=	session('user_auth.schoolid');
	    	$map['id']				=	array('not in',$contest['classids']);
	    	$contest['otherclass']	=	M('ClassInfo')->where($map)->select();
	
	    	$this->assign('contest',$contest);
	    	$this->display();
    	} 
    }
    
	/**
	 * 查看比赛详细
	 *
	 * 		获取页面参数，
	 * 			通过比赛id查询多表查询得到该系列内的书目及已读次数。
	 */
	public function detail(){
		$bookGameId	=	I('id');

		//查询比赛信息
		$contest		=	M('BookGame')->find($bookGameId);
		//多表查出图书及已读次数关系
		$bookGameModel	=	M('BookGameStatus bgs')
							->join('primary_book_info bi ON bgs.bookid=bi.id','LEFT');//读书比赛中的书目状态表 左连接图书表查询得到图书名称  查出该书已读总数
		$bookOfSeries	=	$this->	lists($bookGameModel,					//模型
										'bgs.book_game_id='.$bookGameId,	//查询条件where
										'bi.id',							//排序条件order
										'bi.id,bi.bookname,bgs.count_book'	//查询字段field
    								);
		$classGameRelationModel		=	M('ClassGameRelation');
		foreach ($bookOfSeries as $key => $value) {
			//为每本书查询每个班级的阅读次数
			$map['bookid']			=	$value['id'];
			$map['book_game_id']	=	$bookGameId;
			$bookOfSeries[$key]['detail']=	$classGameRelationModel
											->where($map)
											->order('classid')
											->field('read_times')
											->select();
// 			dump($bookOfSeries[$key]);
		}
		//查询表头班级
		$classMap['id']	=	array('in',$contest['classids']);
		$classSnoList	=	M('ClassInfo')
							->where($classMap)
							->order('id')
							->field('class_sno')
							->select();
// 		dump($classSnoList);

// 		dump($bookOfSeries);
		$this->assign('_list',$bookOfSeries);
		$this->assign('class_list',$classSnoList);
		$this->assign('contest',$contest);
// 		dump($contest);
		$this->display();
	}


	/**
	 * 修改状态
	 * @param string $method	传入的修改状态命令
	 *		start			开始比赛
	 *		shutdown		结束比赛
	 *		deletecontest	删除比赛{1：未开始，2：进行中与已结束}
	 */
	public function changeStatus($method=null){
		$map['id'] =   I('id');
		$bookGameModel=D('BookGame');
		switch ( strtolower($method) ){
			//isready 是否开启（0，表示已结束，1，表示未开始，2表示已开始，默认为1）
			//status  状态（-1：已删除，0：禁用，1：正常）
			case 'start':
				$bookGameId =  $bookGameModel->startBookGame($map['id']);
				if(!$bookGameId){
					$this -> error($bookGameModel->getError());
				}else {
					$this -> success('操作成功，比赛已开始！',Cookie('__forward__'));
				}
				break;
			case 'shutdown':
				$data['isready']=0;
				$data['end_time']=NOW_TIME;
				if(!$bookGameModel->where($map)->save($data)){
					$this -> error('结束比赛失败！');
				}else{
					$this -> success('操作成功，比赛已结束！',Cookie('__forward__'));
				}
				break;
			case 'deletecontest':
				$bookGame=$bookGameModel->where($map)->find();
				if($bookGame['isready']==1){//未开始则删除记录
					if(!$bookGameModel->delete($map['id'])){
						$this -> error('删除失败！');
					}else{
						$this -> success('删除成功！',Cookie('__forward__'));
					}
				}else{						//进行中与已结束用status控制
					$this->delete('BookGame', $map);
				}
				break;

			default:
				$this->error('参数非法');
		}
	}
}



